package com.channel.bank.adapter.pay.utils.https;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {


    /**
     * @param requestUrl 请求地址
     * @param method 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @throws Exception
     */
    public static HttpResponse httpsRequest(String requestUrl, String method, String outputStr) throws IOException {
        HttpsURLConnection connection = null;
        try {
            SSLSocketFactory ssf = null;
            try {
                // 创建SSLContext对象，并使用我们指定的信任管理器初始化
                TrustManager[] tm = { new MyX509TrustManager() };
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());
                ssf = sslContext.getSocketFactory();
            } catch (NoSuchAlgorithmException e) {
                throw new IOException("实例化SSLContext失败", e);
            } catch (NoSuchProviderException e) {
                throw new IOException("实例化SSLContext失败", e);
            } catch (KeyManagementException e) {
                throw new IOException("初始化SSLContext失败", e);
            }

            URL url = new URL(requestUrl);
            connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(ssf);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            // 设置请求方式（GET/POST）
            connection.setRequestMethod(method);
            if ("GET".equalsIgnoreCase(method)) {
                connection.connect();
            }

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = connection.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            return new HttpResponse(connection);
        } catch (IOException e) {
            if (connection != null) {
                connection.disconnect();
            }
            throw e;
        }
    }

    /**
     * @param requestUrl 请求地址
     * @param method 请求方式（GET、POST）
     * @param outputStr 提交的数据
     * @throws Exception
     */
    public static HttpResponse httpsRequest2(String requestUrl, String method, String outputStr) throws IOException {
        HttpsURLConnection connection = null;
        try {
            SSLSocketFactory ssf = null;
            try {
                // 创建SSLContext对象，并使用我们指定的信任管理器初始化
                TrustManager[] tm = { new MyX509TrustManager() };
                SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
                sslContext.init(null, tm, new java.security.SecureRandom());
                ssf = sslContext.getSocketFactory();
            } catch (NoSuchAlgorithmException e) {
                throw new IOException("实例化SSLContext失败", e);
            } catch (NoSuchProviderException e) {
                throw new IOException("实例化SSLContext失败", e);
            } catch (KeyManagementException e) {
                throw new IOException("初始化SSLContext失败", e);
            }

            URL url = new URL(null,requestUrl,new sun.net.www.protocol.https.Handler());
            connection = (HttpsURLConnection) url.openConnection();
            connection.setSSLSocketFactory(ssf);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);

            // 设置请求方式（GET/POST）
            connection.setRequestMethod(method);
            if ("GET".equalsIgnoreCase(method)) {
                connection.connect();
            }

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = connection.getOutputStream();
                // 注意编码格式，防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            return new HttpResponse(connection);
        } catch (IOException e) {
            if (connection != null) {
                connection.disconnect();
            }
            throw e;
        }
    }
    
    
    public static String sendChinaPost(String url,String content){
        HttpURLConnection httpURLConnection = null;
        BufferedReader in = null;
        PrintWriter out = null;
        String resultStr = null;
        Map<String,String> resultMap = new HashMap<String,String>();
        if (!StringUtils.isNotBlank(url)) {
        	 resultMap.put("errCode","URLFailed");
             resultStr = JSONObject.fromObject(resultMap).toString();
            return resultStr;
        }

        try {
            URL apiurl = new URL(url);
            httpURLConnection = (HttpURLConnection) apiurl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content_Type","application/json");
            httpURLConnection.setRequestProperty("Accept_Charset","UTF-8");
            httpURLConnection.setRequestProperty("contentType","UTF-8");
            //发送POST请求参数
            out = new PrintWriter(httpURLConnection.getOutputStream());
            out.write(content);
            out.flush();

            //读取响应
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer sb = new StringBuffer();
                String tempStr = null;
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while ((tempStr=in.readLine()) != null){
                	sb.append(tempStr);
                }
                System.out.println("Post请求返回结果:"+sb.toString());

                //转换成json对象
                /*com.alibaba.fastjson.JSONObject respJson = JSON.parseObject(content.toString());
                String resultCode = respJson.getString("errCode");
                resultMap.put("errCode",resultCode);
                resultMap.put("respStr",respJson.toString());
                resultStr = JSONObject.fromObject(resultMap).toString();*/
                
                resultStr = sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errCode","HttpURLException");
            resultMap.put("msg","调用银商接口出现异常："+e.toString());
            resultStr = JSONObject.fromObject(resultMap).toString();
            return resultStr;
        }finally {
            if (out != null) {
                out.close();
            }
            httpURLConnection.disconnect();
        }

        System.out.println("resultStr:"+resultStr);
        return resultStr;
    }

}

